﻿using System.Collections.ObjectModel;
using System.Net;
using System.Windows;
using GalaSoft.MvvmLight.Command;
using TemperatureWP.Model;

namespace TemperatureWP.ViewModel
{
    public class SettingsViewModel : ExtendedViewModelBase
    {
        private TemperatureModel _temperatureModel;

        public SettingsViewModel()
        {
            // Initialize commands
            UserSelectedItem = new RelayCommand<TemperatureModel>(SelectedItem);

            // Initialize collection
            TemperatureCollection = ThisApp.TemperatureCollection;
        }
        
        // Properties
        public ObservableCollection<TemperatureModel> TemperatureCollection { set; get; }

        public RelayCommand<TemperatureModel> UserSelectedItem { get; set; }

        // Methods
        private void SelectedItem(TemperatureModel temperatureModel)
        {
            _temperatureModel = temperatureModel;

            var uri = string.Format(temperatureModel.Active 
                ? "http://temperaturerest.cloudapp.net/Sensor/{0}/Deactivate/" 
                : "http://temperaturerest.cloudapp.net/Sensor/{0}/Activate/", temperatureModel.Id);

            SendData(uri, GetResponse);
        }

        private void GetResponse(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(string.Format("Error: {0}", e));
                return;
            }

            // Override selected temperature model with changes
            // Since TemperatureCollection is a reference to ThisApp.TemperatureCollection
            // the changes are passed on.
            foreach (var item in TemperatureCollection)
            {
                if (item.Id == _temperatureModel.Id)
                    item.Active = !_temperatureModel.Active;
            }
        }
    }
}
